package org.train.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.train.dao.UserDao;
import org.train.entity.User;
import org.train.util.R;
import org.train.util.RUtil;
import org.train.util.Renum;

@Service
public class UserService implements UserDetailsService{
    @Autowired
    private UserDao dao;
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException{
        User user = dao.selectOne(new QueryWrapper<User>()
                .eq("name", username));
        if(user == null){
            throw new UsernameNotFoundException("用户" + username + "不存在");
        }
        return user;
    }

    public R saveUser(User user){
        if(dao.exists(new QueryWrapper<User>()
                .eq("name", user.getUsername()))){
            return RUtil.error(Renum.REPEAT_USERNAME );
        }

        user.setPassword(passwordEncoder.encode(user.getPassword()));
        if(dao.insert(user) > 0){
            return RUtil.success();
        }
        return RUtil.error(Renum.REGISTER_FAIL);
    }

}
